/*
 * File:    DefaultWhitelistVerifier.java
 * Created: 02-Feb-2008
 * Version: $Id$
 *
 * COPYRIGHT (C) 2008, Bitgate Software, LLC.  All Rights Reserved.
 *
 * software@bitgatesoftware.com
 */

package com.bitgate.util.service.acl;

import java.net.Socket;
import java.util.ArrayList;

import com.bitgate.util.config.Config;
import com.bitgate.util.wildcard.Wildcard;

import static com.bitgate.util.debug.Debug.debug;

/**
 * This is the default Whitelist verifier.
 * 
 * @author kenji
 */
public class DefaultWhitelistVerifier implements AddressVerifierInterface
{
	private final ArrayList<String> accessList;
	
	/**
	 * Constructor.
	 */
	public DefaultWhitelistVerifier() {
		accessList = new ArrayList<String>();
		
		int numAcl = Integer.parseInt(Config.getDefault().parseConfig("acl", "count(/acl/object[@type='white']/property)"));
		
		for(int i = 1; i < (numAcl + 1); i++) {
			String acl = Config.getDefault().parseConfig("acl", "/acl/object[@type='white']/property[" + i + "]/@value");
			
			debug("White ACL = '" + acl + "'");
			
			accessList.add(acl);
		}
	}
	
	/**
	 * Performs a match check against the {@link Socket} passed.
	 * 
	 * @param address {@link Socket} containing the currently active connection.
	 * @return <code>true</code> if blacklisted, <code>false</code> otherwise.
	 */
	public boolean matches(Socket address) {
		String remoteAddress = address.getRemoteSocketAddress().toString();
		
		if (remoteAddress.indexOf('/') != -1) {
			remoteAddress = remoteAddress.substring(remoteAddress.indexOf('/') + 1);
		}
		
		if (remoteAddress.indexOf(":") != -1) {
			remoteAddress = remoteAddress.substring(0, remoteAddress.indexOf(":"));
		}
		
		debug("Checking address '" + remoteAddress + "'");
		
		for(int i = 0; i < accessList.size(); i++) {
			if (remoteAddress.matches(Wildcard.toRegexp(accessList.get(i)))) {
				return true;
			}
		}
		
		return false;
	}
}